﻿function ECommerceRecentViewModel(context) {

    var self = this;

    var spinner = new SpinnerModel();

    var ready = ko.observable(false);
    
    var products = context.recentProducts;

    var productInfoRoute = context.spaRuntime.findRouteByName('product');

    function reloadProduct(id, index) {
        var api = context.api();
        spinner.enter();
        api.products.getById(id, function (data) {
            spinner.leave();
            var res = products();
            res[index] = new FullProductModel(data);
            products(res);
        }, function () {
            spinner.leave();
        });
    }
    
    function reload() {
        var api = context.api();
        spinner.enter();
        api.session.getByUser(10, function (data) {
            spinner.leave();
            var res = [];
            for (var i = 0; i < data.length; i++) {
                res[i] = new FullProductModel();
                reloadProduct(data[i], i);
            }
            products(res);
            ready(true);
        }, function () {
            spinner.leave();
            products([]);
        });
    }
    
    function getProductUrl(product) {
        return productInfoRoute.formatHash({
            id: product.id()
        });
    }

    context.api.subscribe(reload);

    reload();

    self.spinner = spinner;
    self.reload = reload;
    self.products = products;
    self.getProductUrl = getProductUrl;
    self.ready = ready;
}